<template>
  <div class="container">
    <h3>角色列表</h3>
    <el-form :inline="true">
      <el-form-item label="角色名" size="small">
        <el-input v-model="searchRoleName" placeholder="角色名" />
      </el-form-item>
      <el-form-item size="small">
        <el-button type="primary" @click="searchByRoleName">查询</el-button>
      </el-form-item>
      <el-form-item size="small">
        <el-button
          type="primary"
          @click="
            () => {
              searchRoleName = '';
              searchByRoleName();
            }
          "
        >
          重置
        </el-button>
      </el-form-item>
      <el-form-item size="small">
        <el-button type="success" @click="clickAddRole">添加</el-button>
      </el-form-item>
      <el-form-item size="small">
        <el-popconfirm
          title="确定批量删除吗？"
          @onConfirm="batchDeleteByRoleIds()"
        >
          <el-button
            slot="reference"
            type="danger"
            :disabled="selectedIds.length === 0"
          >
            批量删除
          </el-button>
        </el-popconfirm>
      </el-form-item>
    </el-form>
    <el-dialog
      :title="roleInfoDialogType === 'add' ? '添加' : '编辑'"
      :visible="roleInfoDialogType !== ''"
      width="30%"
      @close="roleInfoDialogType = ''"
    >
      <el-form label-position="left" label-width="80px" :model="role">
        <el-form-item label="角色名">
          <el-input v-model="role.roleName" />
        </el-form-item>
        <el-form-item label="角色编码">
          <el-input v-model="role.roleCode" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="role.description" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleInfoDialogType = ''">取 消</el-button>
        <el-button type="primary" @click="roleAction()"> 确 定 </el-button>
      </span>
    </el-dialog>
    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      :v-loading="listLoading"
      element-loading-text="Loading"
      @select="handleTableSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{ limit * (page - 1) + 1 + scope.$index }}
        </template>
      </el-table-column>
      <el-table-column label="角色名">
        <template slot-scope="scope">
          {{ scope.row.roleName }}
        </template>
      </el-table-column>
      <el-table-column label="角色编码">
        <template slot-scope="scope">
          {{ scope.row.roleCode }}
        </template>
      </el-table-column>
      <el-table-column label="描述">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间">
        <template slot-scope="scope">
          {{ scope.row.updateTime }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="170">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            style="background-color: #5da3f8; width: 40px; margin-right: 10px"
            @click="clickUpdateRole(scope.row)"
          >
            <i class="el-icon-edit" style="color: white" />
          </el-button>
          <el-popconfirm
            title="确定删除吗？"
            @onConfirm="deleteByRoleId(scope.row.id)"
          >
            <el-button
              slot="reference"
              type="danger"
              size="mini"
              style="width: 40px; margin-right: 10px"
            >
              <i class="el-icon-delete" style="color: white" />
            </el-button>
          </el-popconfirm>
          <el-button
            type="warning"
            size="mini"
            style="width: 40px"
            @click="beginMenuAuth(scope.row.id)"
          >
            <i class="el-icon-key" style="color: white" />
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin: 5px 10px; display: flex; justify-content: center">
      <el-pagination
        :current-page="page"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
      title="角色授权"
      :visible="isMenuAuthing"
      width="30%"
      @close="isMenuAuthing = false"
      @open="afterOpenMenuAuthDialog"
    >
      <el-tree
        ref="menuTreeRef"
        :data="menuNodes"
        :props="menuTreeProps"
        :check-strictly="true"
        node-key="id"
        default-expand-all
        style="height: 400px; overflow: auto"
        show-checkbox
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="isMenuAuthing = false">取 消</el-button>
        <el-button type="primary" @click="doMenuAuth()"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getPageList,
  deleteById,
  add,
  updateById,
  batchDelete,
  findMenuByRoleId,
  authMenu,
} from "@/api/system/role";

let findMenuByRoleIdRes = {};

export default {
  // 定义初始值
  data() {
    return {
      listLoading: true,
      list: [], // 角色列表
      total: 0, // 总记录数
      page: 1, // 当前页
      limit: 5, // 每页显示记录数
      searchObj: {}, // 条件查询封装对象
      searchRoleName: "",
      roleInfoDialogType: "",
      role: {},
      selectedIds: [],
      isMenuAuthing: false,
      menuNodes: [],
      menuTreeProps: { label: "name", children: "children" },
      currentRoleId: "",
    };
  },
  // 页面渲染之前执行
  created() {
    this.fetchData();
  },
  methods: {
    // 具体方法
    fetchData(pageNum = 1) {
      this.listLoading = true;
      // 发送 ajax 请求
      this.page = pageNum;
      getPageList(this.page, this.limit, this.searchObj)
        .then((response) => {
          this.list = response.data.records;
          this.total = response.data.total;
          // this.listLoading = false;
        })
        .catch(() => {
          // this.listLoading = false;
        });
    },
    handleSizeChange(val) {
      this.limit = val;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.fetchData(val);
    },
    searchByRoleName() {
      if (this.searchRoleName) {
        this.searchObj = { roleName: this.searchRoleName };
      } else {
        this.searchObj = {};
      }
      this.fetchData();
    },
    deleteByRoleId(id) {
      deleteById(id).then(() => {
        this.fetchData();
      });
    },
    clickAddRole() {
      this.roleInfoDialogType = "add";
      this.role = {};
    },
    roleAction() {
      if (this.roleInfoDialogType === "add") {
        add(this.role).then(() => {
          this.fetchData();
        });
      } else if (this.roleInfoDialogType === "edit") {
        updateById(this.role).then(() => {
          this.fetchData();
        });
      }
      this.roleInfoDialogType = "";
    },
    clickUpdateRole(role) {
      this.roleInfoDialogType = "edit";
      this.role = {
        id: role.id,
        roleName: role.roleName,
        roleCode: role.roleCode,
        description: role.description,
      };
    },
    handleTableSelectionChange(rows) {
      this.selectedIds = rows.map((e) => e.id);
    },
    batchDeleteByRoleIds() {
      batchDelete(this.selectedIds).then(() => {
        this.selectedIds = [];
        this.fetchData();
      });
    },
    async beginMenuAuth(roleId) {
      this.currentRoleId = roleId;
      findMenuByRoleIdRes = await findMenuByRoleId(this.currentRoleId);
      this.isMenuAuthing = true;
    },
    async afterOpenMenuAuthDialog() {
      this.menuNodes = findMenuByRoleIdRes.data.sysMenus || [];
      this.$nextTick(() => {
        this.$refs.menuTreeRef.setCheckedKeys(
          findMenuByRoleIdRes.data.checkedIds || [],
          true
        );
      });
    },
    async doMenuAuth() {
      const roleId = this.currentRoleId;
      const menuIdList = this.$refs.menuTreeRef.getCheckedKeys();
      await authMenu({ roleId, menuIdList });
      this.isMenuAuthing = false;
      this.$message({
        message: "角色菜单权限更新成功",
        type: "success",
      });
    },
  },
};
</script>

<style scoped>
.container {
  padding: 5px 10px;
}
</style>
